<?php
namespace app\index\controller;

use think\Controller;
class Auths extends Controller
{
    public function index()
    {
        $shareId = I('param.shareId');
        $params = '';
        if ($shareId){
            $params = '?shareId='.$shareId;
        }
        $wx = new \app\index\model\Wx();
        return $wx->getopenId(config('authurl').$params,config('httpurl'));
    }
    function indexs()
    {
        $shareId = I('param.shareId');
        $wx = new \app\index\model\Wx();
        
        $appId = $wx->configs['APPID'];
        $secret = $wx->configs['APPSECRET'];
        //获取回调微信传入的code，以及自己的参数
        $code = I('get.code');
        
        if (session($code)){
            $this->redirect('Index/index');
        }

        $tokens = $wx->getToken($appId, $secret, $code);
        $userinfo = $wx->getUserInfo($tokens['access_token'], $tokens['openid']);
        
        
        $info['openid'] = $userinfo['openid'];
        $info['nickname'] = $userinfo['nickname'];
        $info['sex'] = $userinfo['sex'];
        $info['imgurl'] = $userinfo['headimgurl'];
        $user = new \app\index\model\User();
        $Tmp = $user->addUser($info);
        $user_id = $Tmp['id'];
        if ($shareId&&$shareId!=$Tmp['share_id']){
            $shareUser = $user->getUserByShareId($shareId);
            if ($shareUser){
                $user->addShareUser($shareUser['id'], $user_id);
            }
            
        }
        $infoTOken['access_token'] = $tokens['access_token'];
        $infoTOken['user_id'] = $user_id;
        $user->addToken($infoTOken);
        session(config('httpurl'),$info['openid']); 
        session($code,$tokens['openid']);
        $this->redirect('Index/index');
    }
    
    
    
}
